# -*- coding: utf-8 -*-
from odoo import models, fields, api, tools, _
from odoo.exceptions import ValidationError, Warning
import datetime
from lxml import etree

from . import attr_template


class LiftFactory(models.Model):
    """
    电梯生产厂家
    """
    _name = 'tyibs.base.lift.factory'

    name = fields.Char(string=u'名称', size=100, required=True)

    # 联系信息
    contact = fields.Char(string=u"联系人", size=100)
    phone = fields.Char(string=u"固定电话", size=30)
    mobile = fields.Char(string=u"手机号码", size=30)
    email = fields.Char(string=u"电子邮件", size=100)
    # 地址信息
    province_id = fields.Many2one('tyibs.base.province', string=u'所属省份')
    city_id = fields.Many2one('tyibs.base.province.city', string=u'所属城市', domain="[('province_id', '=', province_id)]",)
    area_id = fields.Many2one('tyibs.base.province.city.area', string=u'所属区', domain="[('city_id', '=', city_id)]",)
    address = fields.Char(string=u"详细地址", size=300)

    model_ids = fields.One2many('tyibs.base.lift.factory.model', 'factory_id', string=u'电梯型号')
    remark = fields.Text(string=u'备注')


class LiftModel(models.Model):
    """
    产品型号
    """
    _name = 'tyibs.base.lift.factory.model'

    factory_id = fields.Many2one('tyibs.base.lift.factory', string=u'厂家', required=True)
    name = fields.Char(string=u'名称', size=100, required=True)
    remark = fields.Text(string=u'备注')

    
class LiftBrand(models.Model):
    """
    品牌
    """
    _name = 'tyibs.base.lift.brand'

    name = fields.Char(string=u'名称', size=100, required=True)
    remark = fields.Text(string=u'备注')

    _sql_constraints = [
        ("unique_name", "unique(name)", u"电梯品牌已经存在")
    ]


class LiftBigCategory(models.Model):
    """
    电梯大类，设备类别,因为是后加的对象，本来应该是category，下面是subcategory
    """
    _name = "tyibs.base.lift.big.category"
    name = fields.Char(string=u"设备类别", size=100, required=True)
    # A B C D
    code = fields.Char(string=u"编码", size=10)
    sub_category_ids = fields.One2many("tyibs.base.lift.category", "big_category_id", string=u"子类")
    remark = fields.Text(string=u'备注')

    _sql_constraints = [
        ("unique_name", "unique(name)", u"设备类别已经存在"),
        ("unique_code", "unique(code)", u"设备类别编码已经存在"),
    ]


class LiftCategory(models.Model):
    """
    电梯类型,设备名称
    """
    _name = 'tyibs.base.lift.category'

    big_category_id = fields.Many2one("tyibs.base.lift.big.category", string=u"设备名称", required=True)
    name = fields.Char(string=u'名称', size=100, required=True)
    remark = fields.Text(string=u'备注')

    _sql_constraints = [
        ("unique_name", "unique(name)", u"设备名称已经存在")
    ]


class LiftPlace(models.Model):
    """
    使用场所
    """
    _name = 'tyibs.base.lift.place'

    name = fields.Char(string=u'名称', size=100, required=True)


class Lift(models.Model):
    """
    电梯资料
    """
    _name = "tyibs.base.lift"
    # code 虽然唯一但是很多是没有的，不能被其他地方选择搜索
    _rec_name = "factory_number"

    @api.model
    def _get_default_attributes(self, attr_template):
        return [(0, 0, {'name': item['name'], 'code': item['code'], 'value': ''}) for item in attr_template]

    @api.model
    def _get_default_control_attrs(self):
        return self._get_default_attributes(attr_template.CONTROL_ATTR_TEMPLATE)

    @api.model
    def _get_default_traction_machine_attrs(self):
        return self._get_default_attributes(attr_template.DRAG_ATTR_TEMPLATE)

    @api.model
    def _get_default_car_attrs(self):
        return self._get_default_attributes(attr_template.SEDAN_ATTR_TEMPLATE)

    @api.model
    def _get_default_overspeed_attrs(self):
        return self._get_default_attributes(attr_template.SPEED_LIMITER_ATTR_TEMPLATE)

    @api.model
    def _get_default_bearing_attrs(self):
        return self._get_default_attributes(attr_template.BEARING_ATTR_TEMPLATE)

    @api.model
    def _get_default_other_attrs(self):
        return self._get_default_attributes(attr_template.OTHER_ATTR_TEMPLATE)

    province_id = fields.Many2one("tyibs.base.province", string=u'省份', required=True, default=lambda self:self.env["tyibs.base.province"].search([('is_default','=',True)],limit=1).id or False)
    city_id = fields.Many2one("tyibs.base.province.city", string=u"城市", domain="[('province_id','=',province_id)]", required=True, default=lambda self:self.env["tyibs.base.province.city"].search([('is_default','=',True)],limit=1).id or False)
    area_id = fields.Many2one("tyibs.base.province.city.area", string=u"区/县", domain="[('city_id','=',city_id)]", required=True)
    town_id = fields.Many2one("tyibs.base.province.city.area.town", string=u"行政区域", domain="[('area_id','=',area_id)]")

    register_code = fields.Char(string=u'设备注册代码',size=100)
    user_inside_code = fields.Char(string=u'使用单位内部编码', size=30)
    code = fields.Char(string=u'电梯编号', size=20)
    import_code = fields.Char(string=u"导入的电梯编号")
    update_time = fields.Date(string=u"更新日期")
    rfid_code = fields.Char(string=u"RFID号")

    use_address = fields.Char(string=u'电梯地址', required=False, size=100)
    gps_address = fields.Char(string=u"GPS地址")
    ln = fields.Float(string=u"地点经度", digits=(32,6))
    la = fields.Float(string=u"地点纬度", digits=(32,6))
    bind_image = fields.Binary(string=u"绑定照片", attachment=True, public=True)

    big_category_id = fields.Many2one("tyibs.base.lift.big.category", string=u"设备类别")
    category_id = fields.Many2one("tyibs.base.lift.category", string="设备名称", domain="[('big_category_id','=',big_category_id)]")
    register_date = fields.Date(string=u"注册登记日期")

    # 质监管理单位
    qs_company_id = fields.Many2one("tyibs.base.qs.company", string=u"监管单位")

    # 电梯维保单位信息
    maintenance_company_id = fields.Many2one("tyibs.base.maintenance.company", string=u"维保公司名称")
    last_maintenance_company_id = fields.Many2one("tyibs.base.maintenance.company", string=u"上家维保公司")
    maintenance_company_contact = fields.Char(related="maintenance_company_id.contact", string=u"维保公司联系人")
    maintenance_company_mobile = fields.Char(related="maintenance_company_id.mobile", string=u"联系人手机")

    maintenance_site_id = fields.Many2one("tyibs.base.maintenance.company.site", string=u"维保公司站点", domain="[('enterprise_id','=',maintenance_company_id)]")
    maintenance_salvager_id = fields.Many2one("tyibs.base.maintenance.company.salvager", string=u"维保救援人员", domain="[('enterprise_id','=', maintenance_company_id)]")
    maintenance_salvager_mobile = fields.Char(related="maintenance_salvager_id.mobile", string=u"救援人员电话", store=True)
    last_maintenance_date = fields.Date(string=u'上次维保日期')
    # 电梯使用单位信息
    use_company_id = fields.Many2one("tyibs.base.lift.use.company", string=u"使用单位名称")
    use_company_contact = fields.Char(related="use_company_id.linkman", string=u"使用单位联系人")
    use_company_mobile = fields.Char(related="use_company_id.linkman_phone", string=u"使用单位联系人手机")
    # 电梯救援单位信息
    salvager_unit_id = fields.Many2one("tyibs.base.maintenance.company", string="救援单位", domain="[('is_salvager_unit','=', True)]")
    salvager_site_id = fields.Many2one("tyibs.base.maintenance.company.site", string="救援站点", domain="[('enterprise_id','=', salvager_unit_id)]")

    # 基本信息
    street_manager = fields.Char(string=u"所在地居委会", size=100)
    factory_id = fields.Many2one("tyibs.base.lift.factory", string=u'生产厂家', ondelete="set null")
    model_id = fields.Many2one('tyibs.base.lift.factory.model', string=u'电梯型号', domain="[('factory_id', '=', factory_id)]", ondelete="set null")
    place_id = fields.Many2one('tyibs.base.lift.place', string=u'使用场所', ondelete="set null")
    last_plan_check_date = fields.Date(string=u'上次计划检验日期')
    last_check_date = fields.Date(string=u'上次实际检验日期')
    next_check_date = fields.Date(string=u'下次检验日期')
    checkout_result = fields.Selection([('ok', '合格'), ('no', '不合格'), ('re_ok', '复检合格'), ('re_no', '复检不合格'),('corrective','整改期间')], string=u"检验结论")

    card_install_state = fields.Selection([('uninstall','未安装'),('installed','安装')], string=u'是否安装标识牌', default='uninstall')
    is_join_protect = fields.Selection([('yes', u'是'),('no', u'否')], string=u'是否参保')

    drag_way = fields.Selection([('ac_double_speed', '交流双速'), ('speedgoverningb','调压调速'), ('frequency_conversion','变频'), ('other', '其他')], string=u'拖动方式')
    lift_status = fields.Selection([('using','在用'),('unused','停用'),('cancel','注销')], string=u'电梯状态')
    maintenance_type = fields.Selection([('orig_factory','原厂维保'),('entrust','授权委托'),('third_party','第三方维保'),('user','使用单位维保')], string=u'维保类型')

    made_date = fields.Date(string=u"制造日期")
    install_date = fields.Date(string=u'安装日期')
    lowest_floor = fields.Integer(string=u'最低楼层')
    highest_floor = fields.Integer(string=u'最高楼层')
    lift_age = fields.Selection([('under_five_years','5年以下'),('five_to_ten_years','5~10年'),('ten_to_fifteen_years','10~15年'),('above_fifteen_years','15年以上')], string=u"使用年限")

    rated_load_weight = fields.Float(string=u'额定载重(KG)')
    rated_speed = fields.Float(string=u'额定速度(M/S)')

    drag_height = fields.Float(string=u"提升高度(M)")
    drag_floor_count = fields.Integer(string=u"层数量")
    drag_site_count = fields.Integer(string=u"站数量")
    drag_door_count = fields.Integer(string=u"门数量")
    stage_width = fields.Float(string=u"梯级宽度")

    control_way = fields.Char(string=u'控制方式', size=20)

    # todo 使用编号是否有重复，坑底、机房、轿顶设备号待定
    user_device_code = fields.Char(string=u'使用设备编号', size=30)
    factory_number = fields.Char(string=u'出厂编号', size=50, required=True)
    register_organ = fields.Char(string=u'注册登记机构', size=50)
    device_operator = fields.Char(string=u'设备操作人员', size=20)
    rated_passenger_num = fields.Integer(string=u'可乘人数')
    open_way = fields.Char(string=u'开门方式', size=20)

    device_check_organ = fields.Char(string=u'设备检验机构', size=50)

    maintenance_manager = fields.Char(string=u'维保负责人', size=50)
    maintenance_manager_phone = fields.Char(string=u'维保负责人手机', size=50)

    property_right_unit = fields.Char(string=u'电梯产权单位', size=100)

    # has_register = fields.Boolean(u"是否注册", default=False)
    register_status = fields.Selection([('unregistered', '未注册'), ('registering', '注册中'), ('registered', '已注册')], string=u"注册状态", default="unregistered")
    install_unit = fields.Char(u"安装单位", size=100)

    control_attr_ids = fields.One2many("tyibs.base.lift.control.attr", "lift_id", string=u'控制器',  default=_get_default_control_attrs)
    traction_machine_attr_ids = fields.One2many("tyibs.base.lift.traction.machine.attr", "lift_id", string=u'曳引机', default=_get_default_traction_machine_attrs)
    car_attr_ids = fields.One2many("tyibs.base.lift.car.attr", "lift_id", string=u'轿厢', default=_get_default_car_attrs)
    overspeed_attr_ids = fields.One2many("tyibs.base.lift.overspeed.attr", "lift_id", string=u'限速器',  default=_get_default_overspeed_attrs)
    bearing_attr_ids = fields.One2many("tyibs.base.lift.bearing.attr", "lift_id", string=u'轴承', default=_get_default_bearing_attrs)
    other_attr_ids = fields.One2many("tyibs.base.lift.other.attr", "lift_id", string=u'其他参数', default=_get_default_other_attrs)
    comment_ids = fields.One2many("tyibs.base.lift.comment", "lift_id", string=u"电梯时间轴")

    overhaul_unit = fields.Char(string=u"大修/改造单位", size=50)
    overhaul_date = fields.Char(string=u"大修/改造日期")

    _sql_constraints = [
        ("unique_factory_number", "unique(factory_number)", u"出厂编号已经存在")
    ]

    @api.model
    def create(self, vals):
        if vals.get("register_code", False):
            # 有注册代码，默认创建时间即为更新时间
            vals["update_time"] = datetime.datetime.now().strftime("%Y-%m-%d")
        return super(Lift, self).create(vals)

    @api.multi
    def write(self, vals):
        for item in self:
            if vals.get("register_code", False):
                # 有更新注册代码
                vals["update_time"] = datetime.datetime.now().strftime("%Y-%m-%d")
            if vals.get("use_company_id", False) and item.use_company_id.id != int(vals.get("use_company_id")):
                new_use_company = self.env["tyibs.base.lift.use.company"].browse(vals.get("use_company_id"))
                lift_comment_vals = {
                    "lift_id": item.id,
                    "category_id": self.env.ref("lift_base.tyibs_base_lift_comment_category_other").id,
                    "content": u"使用单位由" + (item.use_company_id.name or u"未知") + u"变更为" + (new_use_company.name or u"未知"),
                    "operator_time": datetime.datetime.now(),
                }
                self.env["tyibs.base.lift.comment"].create(lift_comment_vals)
        return super(Lift, self).write(vals)

    # @api.model
    # def search(self, args, offset=0, limit=None, order=None, count=False):
    #     context = self._context or {}
    #     if context.get("search_from", False) == "main_employee":
    #         # 维保员工的后台菜单
    #         args.append(("maintenance_company_id", "=", self.env.user.main_company_id.id))
    #     elif context.get("search_from", False) == "qs_area":
    #         # 区县局的后台菜单
    #         args.append(("area_id", "=", self.env.user.qs_company_id.area_id.id))
    #     elif context.get("search_from", False) == "use_menu":
    #         # 使用单位的后台菜单
    #         args.append(("use_company_id", "=", self.env.user.use_company_id.id))
    #     return super(Lift, self).search(args, offset, limit, order, count)

    # @api.model
    # def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
    #     context = self._context or {}
    #     res = super(Lift, self).fields_view_get(view_id=view_id, view_type=view_type,
    #                                                  toolbar=toolbar, submenu=False)
    #     if (res['type'] == "form" or res['type'] == 'tree'):
    #         doc = etree.XML(res['arch'])
    #         form_xpath = doc.xpath("//{}".format(res['type']))[0]
    #         if context.get("readonly", False):
    #             # asset_id = self.env.context.get('active_id')
    #             # active_model = self.env.context.get('active_model')
    #             # if context.get("form_no_edit", False) == 'no':
    #             form_xpath.set("create", "false")
    #             form_xpath.set("edit", "false")
    #             form_xpath.set("delete", "false")
    #             res['arch'] = etree.tostring(doc)
    #         elif context.get("write_only", False):
    #             form_xpath.set("create", "false")
    #             form_xpath.set("delete", "false")
    #             res['arch'] = etree.tostring(doc)
    #         else:
    #             maintenance_group_id = self.env.ref("lift_base.group_lift_main_company_employee").id
    #             maintenance_manager_group_id = self.env.ref("lift_base.group_lift_main_company_manager").id
    #             group_ids = self.env.user.groups_id.ids
    #             if maintenance_group_id in group_ids and maintenance_manager_group_id not in group_ids:
    #                 form_xpath.set("create", "false")
    #                 form_xpath.set("edit", "false")
    #                 form_xpath.set("delete", "false")
    #                 res['arch'] = etree.tostring(doc)
    #     return res

    def update_all_lift_age(self):
        """
        更新所有的电梯使用年限
        :return:
        """
        current_time = datetime.datetime.now()
        current_date = current_time.strftime("%Y-%m-%d")
        lifts = self.search([('made_date', '!=', False)])
        for lift in lifts:
            if lift.made_date[5:10] >= current_date[5:10]:
                coefficient = (int(current_date[:4]) - int(lift.made_date[:4]) + 1) / 5
            else:
                coefficient = (int(current_date[:4]) - int(lift.made_date[:4])) / 5
            if coefficient == 0:
                lift.lift_age = 'under_five_years'
            elif coefficient == 1:
                lift.lift_age = 'five_to_ten_years'
            elif coefficient == 2:
                lift.lift_age = 'ten_to_fifteen_years'
            elif coefficient > 2:
                lift.lift_age = 'above_fifteen_years'
        return u"更新完成"

    def update_lift_age(self):
        """
        每天更新的电梯使用年限
        :return:
        """
        current_time = datetime.datetime.now()
        current_month_day = current_time.strftime("-%m-%d")
        current_year = current_time.year
        lifts = self.search([('made_date', 'ilike', current_month_day)])
        for lift in lifts:
            coefficient = (current_year - int(lift.made_date[:4])) / 5
            if coefficient == 0:
                lift.lift_age = 'under_five_years'
            elif coefficient == 1:
                lift.lift_age = 'five_to_ten_years'
            elif coefficient == 2:
                lift.lift_age = 'ten_to_fifteen_years'
            elif coefficient > 2:
                lift.lift_age = 'above_fifteen_years'
        return u"更新完成"


class LiftControlAttr(models.Model):
    """
    控制器资料
    """
    _name = "tyibs.base.lift.control.attr"

    lift_id = fields.Many2one("tyibs.base.lift",  ondelete="cascade", string=u'电梯', required=True)
    name = fields.Char(string=u'参数名', required=True, size=100 )
    code = fields.Char(string=u'参数编码', size=100 )
    value = fields.Char(string=u'值', size=100 )


class LiftTractionMachineAttr(models.Model):
    """
    曳引机资料
    """
    _inherit="tyibs.base.lift.control.attr"
    _name = "tyibs.base.lift.traction.machine.attr"


class LiftCarAttr(models.Model):
    """
    轿厢资料
    """
    _inherit="tyibs.base.lift.control.attr"
    _name = "tyibs.base.lift.car.attr"


class LiftOverSpeedAttr(models.Model):
    """
    限速器资料
    """
    _inherit="tyibs.base.lift.control.attr"
    _name = "tyibs.base.lift.overspeed.attr"


class LiftBearingAttr(models.Model):
    """
    轴承资料
    """
    _inherit="tyibs.base.lift.control.attr"
    _name = "tyibs.base.lift.bearing.attr"


class LiftOtherAttr(models.Model):
    """
    其他资料
    """
    _inherit="tyibs.base.lift.control.attr"
    _name = "tyibs.base.lift.other.attr"


class LiftCommentCategory(models.Model):
    """
    电梯信息操作日志分类
    """
    _name = "tyibs.base.lift.comment.category"

    name = fields.Char(string=u"分类名称", size=100, required=True)
    css_class = fields.Char(string=u"图标名称", size=100, required=True)
    remark = fields.Text(string=u'备注')


class LiftComment(models.Model):
    _name = "tyibs.base.lift.comment"
    _rec_name = "category_id"

    lift_id = fields.Many2one("tyibs.base.lift", string=u"所属电梯", required=True, ondelete="cascade")
    category_id = fields.Many2one("tyibs.base.lift.comment.category", string=u"日志分类", required=True)
    category_css_class = fields.Char(related="category_id.css_class", store=True)
    content = fields.Text(string=u"操作内容")
    operator_time = fields.Datetime(string=u"操作时间")
    operator_user_id = fields.Many2one("res.users", string=u"操作用户")
    res_model = fields.Char(string=u"关联模型")
    res_id = fields.Char(string="关联记录")
    remark = fields.Text(string=u'备注')